﻿/*
   Copyright 2013 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using AopAlliance.Intercept;
using Flower.Logging;
using System.Transactions;

namespace Flower.Services.Host
{
    internal class DefaultLogging : IMethodInterceptor
    {   
        private readonly Log _log;

        private long _callNo = 0;

        public DefaultLogging(string source)
        {
            _log = LogManager.CreateLog(source);
        }

        public object Invoke(IMethodInvocation invocation)
        {
            Guid globalTxnId = default(Guid);
            string localTxnId = string.Empty;
            var isolationLevel = IsolationLevel.Unspecified;

            if (Transaction.Current != null)
            {
                localTxnId = Transaction.Current.TransactionInformation.LocalIdentifier;
                globalTxnId = Transaction.Current.TransactionInformation.DistributedIdentifier;
                isolationLevel = Transaction.Current.IsolationLevel;
            }

            long callNo = Interlocked.Increment(ref _callNo);
            _log.Trace(() => string.Format("{0}[{1}]({2}) txn({3}:{4}, {5})", invocation.Method.Name, callNo, GetInvocationArgs(invocation), localTxnId, globalTxnId, isolationLevel));
            
            try
            {
                object retval = invocation.Proceed();
                _log.Trace(() => string.Format("{0}[{1}] returning {2}", invocation.Method.Name, callNo, retval ?? "<null>"));
                return retval;
            }
            catch(Exception ex)
            {
                _log.Error(string.Format("{0}[{1}] failed.", invocation.Method.Name, callNo), ex);
                throw;
            }
        }

        private string GetInvocationArgs(IMethodInvocation invocation)
        {
            return 
                string.Join
                (
                    ", ", 
                    invocation
                        .Method
                        .GetParameters()
                        .Select((prm, i) => string.Concat(prm.Name, " = ", invocation.Arguments[i] ?? "<null>"))
                );
        }
    }
}
